<template>
  <div class="claim-management-container">
    <!-- 页面标题与操作区 -->
    <div class="page-header">
      <h2>{{ currentView === 'list' ? '报案拒赔管理' : '拒赔申请管理' }}</h2>
      <div class="header-actions">
        <el-button
            v-if="currentView === 'reject'"
            @click="switchToView('list')"
            type="primary"
        >
          <el-icon><ArrowLeft /></el-icon>
          返回列表
        </el-button>
      </div>
    </div>

    <!-- 错误提示区域 -->
    <el-alert
        v-if="errorMsg"
        :message="errorMsg"
        type="error"
        show-icon
        closable
        @close="errorMsg = ''"
        style="margin-bottom: 16px"
    />

    <!-- 列表视图 -->
    <template v-if="currentView === 'list'">
      <!-- 筛选条件区 -->
      <el-card shadow="hover" class="filter-card">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="保单编号">
            <el-input
                v-model="filterForm.policyId"
                placeholder="请输入保单编号"
                clearable
                style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="报案状态">
            <el-select
                v-model="filterForm.reportStatus"
                placeholder="请选择状态"
                style="width: 200px"
                @change="handleStatusChange"
            >
              <el-option label="已立案" value="4" />
              <el-option label="待结案" value="7" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getReportList">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 列表展示区 -->
      <el-card shadow="hover" class="list-card">
        <el-table
            :data="tableData"
            border
            stripe
            style="width: 100%"
            :header-cell-style="{ 'text-align': 'center', 'background-color': '#f8f9fa' }"
            :cell-style="{ 'text-align': 'center' }"
            :loading="loading"
            empty-text="暂无符合条件的报案数据"
        >
          <el-table-column label="报案ID" prop="id" width="80" />
          <el-table-column label="报案编号" prop="reportNo" width="200" />
          <el-table-column label="保单编号" prop="policyId" width="180" />
          <el-table-column label="投保人ID" prop="insuredId" width="100" />
          <el-table-column label="灾祸类型" width="120">
            <template #default="scope">
              <el-tag :type="getDisasterTagType(scope.row.disasterType)">
                {{ getDisasterTypeName(scope.row.disasterType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="报案状态" prop="reportStatus" width="140">
            <template #default="scope">
              <el-tag
                  :type="statusMap[scope.row.reportStatus]?.type"
                  :icon="statusMap[scope.row.reportStatus]?.icon"
                  size="small"
              >
                {{ statusMap[scope.row.reportStatus]?.text }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="报案人" prop="reporterName" width="120" />
          <el-table-column label="联系电话" prop="reporterPhone" width="140" />
          <el-table-column label="报案时间" width="200">
            <template #default="scope">
              {{ formatReportTime(scope.row.reportTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="120">
            <template #default="scope">
              <el-button
                  type="danger"
                  size="small"
                  @click="toRejectPage(scope.row)"
                  :loading="scope.row.rejectLoading"
                  icon="CircleClose"
              >
                申请拒赔
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <div class="pagination" style="margin-top: 15px; text-align: right">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageNum"
              :page-sizes="[5, 10, 20, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
          />
        </div>
      </el-card>
    </template>

    <!-- 拒赔视图 -->
    <template v-if="currentView === 'reject'">
      <el-card shadow="hover" class="main-card">
        <!-- 数据概览区域 -->
        <el-collapse
            class="info-collapse"
            v-model="activePanels"
            style="margin-bottom: 24px"
        >
          <!-- 报案基本信息 -->
          <el-collapse-item title="报案基本信息" name="report">
            <el-descriptions column="2" border :column-props="{ span: 12 }">
              <el-descriptions-item label="报案编号" :span="2" class="highlight-item">
                {{ reportInfo.reportNo || '暂无数据' }}
              </el-descriptions-item>
              <el-descriptions-item label="报案人">{{ reportInfo.reporterName || '暂无数据' }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ reportInfo.reporterPhone || '暂无数据' }}</el-descriptions-item>
              <el-descriptions-item label="灾祸类型">{{ getDisasterType(reportInfo.disasterType) }}</el-descriptions-item>
              <el-descriptions-item label="灾祸发生时间">{{ formatDateTime(reportInfo.disasterOccurTime) }}</el-descriptions-item>
              <el-descriptions-item label="损失描述" :span="2">{{ reportInfo.lossDescription || '暂无数据' }}</el-descriptions-item>
              <el-descriptions-item label="农户预估损失(元)">{{ formatCurrency(reportInfo.lossEstimate) }}</el-descriptions-item>
              <el-descriptions-item label="报案状态">
                <el-tag :type="getStatusTagType(currentReportStatus)">{{ statusMap[currentReportStatus]?.text || '未知状态' }}</el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>

          <!-- 保单信息 -->
          <el-collapse-item title="保单信息" name="policy">
            <el-descriptions column="2" border :column-props="{ span: 12 }">
              <el-descriptions-item label="保单编号" :span="2" class="highlight-item">
                {{ policyInfo.policyId || '暂无数据' }}
              </el-descriptions-item>
              <el-descriptions-item label="投保人ID">{{ policyInfo.insuredId || '暂无数据' }}</el-descriptions-item>
              <el-descriptions-item label="投保人姓名">{{ policyInfo.insuredName || '暂无数据' }}</el-descriptions-item>
              <el-descriptions-item label="保险标的">{{ policyInfo.insuranceSubject || '暂无数据' }}</el-descriptions-item>
              <el-descriptions-item label="保险金额(元)">{{ formatCurrency(policyInfo.sumInsured) }}</el-descriptions-item>
              <el-descriptions-item label="保险期间">
                {{ formatDate(policyInfo.startDate) }} 至 {{ formatDate(policyInfo.endDate) }}
              </el-descriptions-item>
              <el-descriptions-item label="缴费状态">{{ getPayStatus(policyInfo.payStatus) }}</el-descriptions-item>
              <el-descriptions-item label="保单状态">{{ getPolicyStatus(policyInfo.policyStatus) }}</el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>

          <!-- 立案信息 -->
          <el-collapse-item title="立案信息" name="registration">
            <template v-if="!hasRegistrationData()">
              <div class="empty-state">
                <el-empty
                    description="当前报案暂无立案信息，请确认是否已完成立案操作"
                >
                  <el-button type="text" @click="fetchRegistrationInfo(currentReportRow.reportNo)">
                    点击重试加载
                  </el-button>
                </el-empty>
              </div>
            </template>
            <el-descriptions v-else column="2" border :column-props="{ span: 12 }">
              <el-descriptions-item label="立案ID" :span="2" class="highlight-item">
                {{ getRegistrationField('registrationId') || '暂无数据' }}
              </el-descriptions-item>
              <el-descriptions-item label="关联报案号" class="highlight-item">
                {{ getRegistrationField('reportNo') || currentReportRow.reportNo || '暂无数据' }}
              </el-descriptions-item>
              <el-descriptions-item label="立案日期">
                {{ formatDateTime(getRegistrationField('registrationTime')) }}
              </el-descriptions-item>
              <el-descriptions-item label="立案金额(元)">
                {{ formatCurrency(getRegistrationField('surveyorLossEstimate')) }}
              </el-descriptions-item>
              <el-descriptions-item label="责任认定">
                {{ getLiabilityType(getRegistrationField('isCovered')) }}
              </el-descriptions-item>
              <el-descriptions-item label="立案操作员">
                {{ getRegistrationField('registrarId') || '暂无数据' }}
              </el-descriptions-item>
              <el-descriptions-item label="立案备注" :span="2">
                {{ getRegistrationField('remark') || '暂无数据' }}
              </el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>

          <!-- 核赔信息（重点修复核赔号显示） -->
          <el-collapse-item title="核赔信息" name="review">
            <template v-if="!hasReviewData()">
              <div class="empty-state">
                <el-empty
                    description="当前报案暂无核赔信息，核赔流程未完成"
                >
                  <el-button type="text" @click="fetchClaimReviewInfo(currentReportRow.reportNo, true)">
                    点击重试加载
                  </el-button>
                </el-empty>
              </div>
            </template>
            <el-descriptions v-else column="2" border :column-props="{ span: 12 }">
              <!-- 核赔号显示优化：增加多字段兼容和显式同步 -->
              <el-descriptions-item label="核赔ID（核赔号）" :span="2" class="highlight-item">
                {{ getReviewField('verificationId', true) || '暂无数据' }}
              </el-descriptions-item>
              <el-descriptions-item label="关联报案号" class="highlight-item">
                {{ getReviewField('reportNo') || currentReportRow.reportNo || '暂无数据' }}
              </el-descriptions-item>
              <el-descriptions-item label="核赔状态">
                {{ getReviewStatus(getReviewField('verificationStatus')) }}
              </el-descriptions-item>
              <el-descriptions-item label="核赔金额(元)">
                {{ formatCurrency(getReviewField('finalPayAmount')) }}
              </el-descriptions-item>
              <el-descriptions-item label="核赔意见">
                {{ getReviewField('verificationOpinion') || '暂无数据' }}
              </el-descriptions-item>
              <el-descriptions-item label="核赔操作员">
                {{ getReviewField('verifierId') || '暂无数据' }}
              </el-descriptions-item>
              <el-descriptions-item label="核赔时间" :span="2">
                {{ formatDateTime(getReviewField('verificationTime')) }}
              </el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>
        </el-collapse>

        <!-- 拒赔申请表单 -->
        <el-form
            ref="rejectFormRef"
            :model="rejectForm"
            label-width="160px"
            :rules="rejectRules"
            class="reject-form"
            :disabled="submitLoading"
        >
          <!-- 关联字段（只读） -->
          <el-form-item label="拒赔ID" prop="rejectionId">
            <el-input v-model="rejectForm.rejectionId" readonly placeholder="系统自动生成" />
          </el-form-item>
          <el-form-item label="报案编号" prop="reportNo" required>
            <el-input v-model="rejectForm.reportNo" readonly />
          </el-form-item>
          <el-form-item label="立案号" prop="registrationId">
            <el-input
                v-model="rejectForm.registrationId"
                readonly
                placeholder="无立案信息时显示为空"
            />
          </el-form-item>
          <!-- 新增：核赔号表单字段，与概览区域数据同步 -->
          <el-form-item label="核赔号" prop="verificationId">
            <el-input
                v-model="rejectForm.verificationId"
                readonly
                placeholder="无核赔信息时显示为空"
            />
          </el-form-item>
          <el-form-item label="保单编号" prop="policyId" required>
            <el-input v-model="rejectForm.policyId" readonly />
          </el-form-item>

          <!-- 拒赔核心字段 -->
          <el-form-item label="拒赔操作人员" prop="userId" required>
            <el-select
                v-model="rejectForm.userId"
                placeholder="请选择拒赔操作人员"
                clearable
                filterable
                style="width: 100%"
            >
              <el-option
                  v-for="staff in operatorOptions"
                  :key="staff.workNo"
                  :label="`${staff.realName}（工号：${staff.workNo}）`"
                  :value="staff.workNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="拒赔原因" prop="rejectReason" required>
            <el-input
                v-model="rejectForm.rejectReason"
                type="textarea"
                rows="4"
                placeholder="请详细说明拒赔原因（如：不符合保单条款第X条、材料不全、不属于保险责任等）"
            />
            <div class="el-form-item__help">
              <span class="text-warning">! 拒赔原因需至少20个字符，且需详细准确</span>
              <span class="char-count">{{ rejectForm.rejectReason.length }}/20</span>
            </div>
          </el-form-item>
          <el-form-item label="拒赔状态" prop="rejectStatus" required>
            <el-select v-model="rejectForm.rejectStatus" placeholder="请选择拒赔状态" style="width: 100%" disabled>
              <el-option label="待审核" value="1" />
            </el-select>
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item class="form-actions">
            <el-button @click="handleReset" :disabled="submitLoading">重置</el-button>
            <el-button
                type="primary"
                @click="handleSubmit"
                :loading="submitLoading"
            >
              提交拒赔申请
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </template>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox, ElLoading, ElEmpty} from 'element-plus'
import {
  CheckCircle,
  FolderChecked,
  ArrowLeft,
  CircleClose
} from '@element-plus/icons-vue'
import axios from 'axios'
import hxxp from "@/utils/hxxp";

// 路由实例
const router = useRouter()

// ---------------------- 1. 核心状态定义 ----------------------
// 视图状态（list：列表，reject：拒赔表单）
const currentView = ref('list')
// 当前选中的报案行数据
const currentReportRow = ref({})
// 当前报案状态
const currentReportStatus = ref('')
// 错误提示信息
const errorMsg = ref('')
// 折叠面板激活状态
const activePanels = ref(['report', 'registration', 'review'])

// ---------------------- 2. 列表视图数据 ----------------------
const loading = ref(false)
const filterForm = reactive({
  policyId: '',
  reportStatus: '4' // 默认筛选“已立案”状态
})
const pageNum = ref(1)
const pageSize = ref(5)
const total = ref(0)
const tableData = ref([])

// ---------------------- 3. 拒赔视图数据 ----------------------
const submitLoading = ref(false)
const rejectFormRef = ref(null)
const reportInfo = reactive({})
const policyInfo = reactive({})
const registrationInfo = reactive({})
const claimReviewInfo = reactive({})
const operatorOptions = ref([])

// 生成拒赔ID
const generateRejectionId = () => {
  const date = new Date()
  const dateStr = `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, "0")}${String(date.getDate()).padStart(2, "0")}`
  const randomStr = Math.floor(Math.random() * 1000000).toString().padStart(6, "0")
  return `REJ${dateStr}${randomStr}`
}

// 拒赔表单数据（新增核赔号字段）
const rejectForm = reactive({
  rejectionId: generateRejectionId(),
  reportNo: "",
  registrationId: "",
  verificationId: "", // 新增：核赔号字段
  policyId: "",
  userId: "",
  rejectReason: "",
  rejectStatus: "1" // 默认为待审核
})

// 表单验证规则
const rejectRules = reactive({
  reportNo: [
    {required: true, message: "报案编号不能为空", trigger: "blur"}
  ],
  policyId: [
    {required: true, message: "保单编号不能为空", trigger: "blur"}
  ],
  userId: [
    {required: true, message: "请选择拒赔操作人员", trigger: "change"}
  ],
  rejectReason: [
    {required: true, message: "请填写拒赔原因", trigger: "blur"},
    {min: 20, message: "拒赔原因需至少20个字符", trigger: "blur"}
  ],
  rejectStatus: [
    {required: true, message: "请选择拒赔状态", trigger: "change"}
  ]
})

// ---------------------- 4. 字典映射 ----------------------
const statusMap = {
  "4": {text: '已立案', type: 'processing', icon: CheckCircle},
  "7": {text: '待结案', type: 'warning', icon: FolderChecked},
  "10": {text: '已拒赔', type: 'danger', icon: CircleClose}
}

const reviewStatusMap = {
  "1": "待核赔",
  "2": "核赔中",
  "3": "核赔通过",
  "4": "核赔驳回",
  "": "未核赔"
}

const disasterTypeMap = {
  '1': '暴雨', '2': '洪水', '3': '病虫害', '4': '疫病', '5': '其他'
}

const liabilityMap = {
  "1": "属于保险责任", "0": "不属于保险责任", "": "未认定"
}

const policyStatusMap = {
  "1": "待生效", "2": "已生效", "3": "已退保", "4": "已过期", "": "未知"
}

const payStatusMap = {
  "1": "待缴费", "2": "缴费中", "3": "缴费成功", "4": "缴费失败", "": "未知"
}

const statusTagTypeMap = {
  "4": "processing",
  "7": "warning",
  "10": "danger"
}

// ---------------------- 5. 工具函数 ----------------------
// 金额格式化
const formatCurrency = (value) => {
  if (!value && value !== 0) return "0.00"
  return Number(value).toFixed(2)
}

// 日期时间格式化
const formatDateTime = (value) => {
  if (!value) return "未填写"
  return value.replace("T", " ").slice(0, 19)
}

// 日期格式化
const formatDate = (value) => {
  if (!value) return "未填写"
  return value.split("T")[0] || "未填写"
}

// 报案时间格式化
const formatReportTime = (timeStr) => {
  if (!timeStr) return ''
  return timeStr.replace('T', ' ')
}

// 灾祸类型文本
const getDisasterType = (typeCode) => {
  return disasterTypeMap[typeCode] || "未知"
}

// 灾祸类型名称（列表用）
const getDisasterTypeName = (typeCode) => {
  return disasterTypeMap[typeCode] || '未知'
}

// 灾祸类型标签样式
const getDisasterTagType = (typeCode) => {
  const tagTypeMap = {
    '1': 'info',    // 暴雨
    '2': 'warning', // 洪水
    '3': 'danger',  // 病虫害
    '4': 'primary', // 疫病
    '5': 'success'  // 其他
  }
  return tagTypeMap[typeCode] || 'default'
}

// 责任认定文本
const getLiabilityType = (isCovered) => {
  return liabilityMap[isCovered?.toString()] || "未知"
}

// 保单状态文本
const getPolicyStatus = (statusCode) => {
  return policyStatusMap[statusCode?.toString()] || "未知"
}

// 缴费状态文本
const getPayStatus = (statusCode) => {
  return payStatusMap[statusCode?.toString()] || "未知"
}

// 状态标签类型
const getStatusTagType = (statusCode) => {
  return statusTagTypeMap[statusCode] || "info"
}

// 核赔状态文本
const getReviewStatus = (statusCode) => {
  return reviewStatusMap[statusCode?.toString()] || "未知"
}

// ---------------------- 6. 立案信息处理 ----------------------
// 检查是否有立案数据
const hasRegistrationData = () => {
  return !!(
      registrationInfo.registrationId ||
      registrationInfo.registration_id ||
      Object.keys(registrationInfo).length > 0
  )
}

// 获取立案字段（兼容下划线命名，并同步到表单）
const getRegistrationField = (fieldName) => {
  const underscoreField = fieldName.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`)
  const value = registrationInfo[fieldName] || registrationInfo[underscoreField]

  // 同步立案号到表单
  if (fieldName === 'registrationId' && value) {
    rejectForm.registrationId = value
  }
  return value
}

// ---------------------- 7. 核赔信息处理（重点修复核赔号显示） ----------------------
// 检查是否有核赔数据
const hasReviewData = () => {
  return !!(
      claimReviewInfo.verificationId ||
      claimReviewInfo.verification_id ||
      claimReviewInfo.reviewId ||
      claimReviewInfo.review_id ||
      claimReviewInfo.claimVerifyId || // 新增：常见核赔号字段名
      claimReviewInfo.claim_verify_id || // 新增：下划线格式
      Object.keys(claimReviewInfo).length > 0
  )
}

// 获取核赔字段（增强版：支持更多字段名并强制同步核赔号到表单）
const getReviewField = (fieldName, forceSync = false) => {
  // 1. 生成可能的字段名变体（支持更多命名格式）
  const underscoreField = fieldName.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`)
  const reviewField = fieldName.replace('verification', 'review') // verificationId → reviewId
  const claimVerifyField = fieldName.replace('verification', 'claimVerify') // verificationId → claimVerifyId
  const reviewUnderscoreField = reviewField.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`)
  const claimVerifyUnderscoreField = claimVerifyField.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`)

  // 2. 尝试从各种可能的字段名中获取值
  const value = claimReviewInfo[fieldName] ||
      claimReviewInfo[underscoreField] ||
      claimReviewInfo[reviewField] ||
      claimReviewInfo[reviewUnderscoreField] ||
      claimReviewInfo[claimVerifyField] ||
      claimReviewInfo[claimVerifyUnderscoreField]

  // 3. 重点：强制同步核赔号到表单（无论何时获取核赔号字段）
  if ((fieldName === 'verificationId' || forceSync) && value) {
    rejectForm.verificationId = value
  }

  return value
}

// ---------------------- 8. 列表视图方法 ----------------------
// 获取报案列表
const getReportList = async () => {
  loading.value = true
  try {
    const res = await policyAxios.get('/aiClaimReport/all', {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        policyId: filterForm.policyId || undefined,
        reportStatus: filterForm.reportStatus || undefined
      }
    })

    if (res.code === 100200) {
      const listData = res.data?.list || res.list || []
      const totalCount = res.data?.total || res.total || 0

      const filteredData = listData.filter(item =>
          item.reportStatus === 4 || item.reportStatus === 7
      )
      tableData.value = filteredData.map(item => ({...item, rejectLoading: false}))
      total.value = totalCount
    } else {
      const errorMsg = res.msg || res.data?.msg || '未知错误'
      ElMessage.error(`获取报案列表失败：${errorMsg}`)
    }
  } catch (err) {
    const errorMsg = err.response?.data?.msg || err.message || '网络请求失败'
    ElMessage.error(`获取报案列表异常：${errorMsg}`)
  } finally {
    loading.value = false
  }
}

// 状态筛选变更
const handleStatusChange = () => {
  pageNum.value = 1
  getReportList()
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.policyId = ''
  filterForm.reportStatus = '4'
  pageNum.value = 1
  getReportList()
}

// 分页大小变更
const handleSizeChange = (val) => {
  pageSize.value = val
  pageNum.value = 1
  getReportList()
}

// 当前页码变更
const handleCurrentChange = (val) => {
  pageNum.value = val
  getReportList()
}

// ---------------------- 9. 视图切换与数据初始化 ----------------------
// 切换视图
const switchToView = (viewType, row = null) => {
  // 切换视图前清空核赔数据，避免缓存旧数据
  Object.assign(claimReviewInfo, {})
  currentView.value = viewType

  if (viewType === 'reject' && row) {
    currentReportRow.value = row
    currentReportStatus.value = row.reportStatus
    initRejectData(row)
  } else if (viewType === 'list') {
    getReportList()
  }
}

// 跳转到拒赔视图
const toRejectPage = (row) => {
  switchToView('reject', row)
}

// 初始化拒赔数据
const initRejectData = async (row) => {
  // 校验row有效性
  if (!row || !row.reportNo) {
    errorMsg.value = "无效的报案数据，无法加载拒赔信息";
    return;
  }

  // 重置所有数据
  Object.assign(reportInfo, {});
  Object.assign(policyInfo, {});
  Object.assign(registrationInfo, {});
  Object.assign(claimReviewInfo, {});
  operatorOptions.value = [];

  // 重置表单（包含核赔号）
  rejectForm.rejectionId = generateRejectionId()
  rejectForm.reportNo = row.reportNo || ""
  rejectForm.registrationId = ""
  rejectForm.verificationId = "" // 重置核赔号
  rejectForm.policyId = ""
  rejectForm.rejectReason = ""
  rejectForm.userId = ""
  rejectForm.rejectStatus = "1"

  // 显示加载
  const loading = ElLoading.service({
    lock: true,
    text: "正在加载报案/保单/立案信息...",
    background: "rgba(255,255,255,0.7)"
  })

  try {
    // 1. 加载报案详情
    const reportSuccess = await fetchReportInfo(row.reportNo)
    if (!reportSuccess) return

    // 2. 加载保单详情
    if (reportInfo.policyId) {
      await fetchPolicyInfo(reportInfo.policyId)
    }

    // 3. 加载立案详情
    if (row.reportStatus === 4 || row.reportStatus === 7) {
      await fetchRegistrationInfo(row.reportNo)
    }

    // 4. 加载核赔信息（重点：增加重试机制）
    const reviewSuccess = await fetchClaimReviewInfo(row.reportNo)
    if (!reviewSuccess) {
      // 主动尝试再次获取，确保不遗漏数据
      await fetchClaimReviewInfo(row.reportNo, true)
    }
    // 强制同步核赔号到表单
    getReviewField('verificationId', true)

    // 5. 加载拒赔操作人员列表
    await fetchOperatorList()

  } finally {
    loading.close()
  }
}

// ---------------------- 10. 数据获取接口（增强核赔信息获取） ----------------------
// 创建请求实例
const createRequestInstance = (baseURL) => {
  const instance = axios.create({
    baseURL,
    timeout: 8000,
    headers: {
      "Content-Type": "application/json;charset=utf-8",
      Authorization: `Bearer ${localStorage.getItem("token") || ""}`
    }
  })

  // 请求拦截器
  instance.interceptors.request.use(config => {
    const token = localStorage.getItem("token")
    if (token) config.headers.Authorization = `Bearer ${token}`
    return config
  }, error => {
    ElMessage.error("请求参数错误，请检查输入")
    return Promise.reject(error)
  })

  // 响应拦截器
  instance.interceptors.response.use(
      response => response.data,
      error => {
        let errorMsg = "请求失败，请重试"
        if (error.response) {
          errorMsg = error.response.status === 401
              ? "登录已过期，请重新登录"
              : error.response.data?.msg || `请求失败（${error.response.status}）`
          if (error.response.status === 401) {
            localStorage.removeItem("token")
            router.push("/login")
          }
        } else if (error.code === "ECONNABORTED") {
          errorMsg = "请求超时，请检查后端服务"
        }
        ElMessage.error(errorMsg)
        return Promise.reject(error)
      }
  )
  return instance
}

// 初始化请求实例
const policyAxios = createRequestInstance("http://localhost:9000")

// 获取报案详情
const fetchReportInfo = async (reportNo) => {
  try {
    const res = await policyAxios.get(`/aiClaimReport/${reportNo}`)
    if (res.code === 100200 && res.data) {
      Object.assign(reportInfo, res.data)
      rejectForm.reportNo = res.data.reportNo
      return true
    } else {
      ElMessage.warning("未查询到报案信息")
      return false
    }
  } catch (error) {
    console.error("获取报案信息失败:", error)
    return false
  }
}

// 获取保单详情
const fetchPolicyInfo = async (policyId) => {
  try {
    const res = await hxxp.get("/aiInsureOrder/getOrder", {
      params: {policyId}
    })
    if (res && res.policyId) {
      Object.assign(policyInfo, res)
      rejectForm.policyId = res.policyId
      return true
    } else {
      ElMessage.warning(`未查询到保单号为${policyId}的信息`)
      return false
    }
  } catch (error) {
    console.error("获取保单信息失败:", error)
    return false
  }
}

// 获取立案详情
const fetchRegistrationInfo = async (reportNo) => {
  try {
    const res = await hxxp.get(`/aiClaimRegistration/getByReportNo/${reportNo}`);

    if (res.code === 100200) {
      if (res.data) {
        Object.assign(registrationInfo, res.data);
        // 兼容下划线命名的字段
        if (res.data.registration_id) {
          registrationInfo.registrationId = res.data.registration_id
        }
        // 同步立案号到表单
        rejectForm.registrationId = registrationInfo.registrationId || res.data.registration_id || "";
        return true;
      } else {
        ElMessage.warning(`报案号${reportNo}暂无立案信息`);
        registrationInfo.reportNo = reportNo;
        return false;
      }
    } else {
      ElMessage.error(`查询立案信息失败: ${res.msg || '未知错误'}`);
      return false;
    }
  } catch (error) {
    console.error("获取立案信息失败:", error);
    if (error.response?.status === 404) {
      ElMessage.error(`立案接口不存在，请检查后端配置: ${error.config.url}`);
    } else {
      ElMessage.error(`获取立案信息异常: ${error.message}`);
    }
    return false;
  }
}

// 获取核赔信息（重点修复：支持多接口、多字段、重试机制）
const fetchClaimReviewInfo = async (reportNo, forceRetry = false) => {
  // 尝试多个可能的接口获取核赔信息
  const apiEndpoints = [
    `/aiClaimVerification/report?reportNo=${reportNo}`,
    `/aiClaimReview/getByReportNo/${reportNo}`,
    `/aiClaimVerify/find?reportNo=${reportNo}`
  ];

  // 尝试获取数据的函数
  const tryFetch = async (endpoint) => {
    try {
      const res = await hxxp.get(endpoint);
      if (res.code === 100200) {
        if (res.data) {
          Object.assign(claimReviewInfo, res.data);

          // 显式映射各种可能的核赔号字段
          const possibleIds = [
            res.data.verificationId,
            res.data.verification_id,
            res.data.reviewId,
            res.data.review_id,
            res.data.claimVerifyId,
            res.data.claim_verify_id
          ];

          // 找到第一个有效的核赔号并设置
          const validId = possibleIds.find(id => id);
          if (validId) {
            claimReviewInfo.verificationId = validId;
            rejectForm.verificationId = validId; // 直接同步到表单
          }

          return true;
        }
      }
      return false;
    } catch (error) {
      console.error(`从接口${endpoint}获取核赔信息失败:`, error);
      return false;
    }
  };

  // 依次尝试所有接口
  for (const endpoint of apiEndpoints) {
    const success = await tryFetch(endpoint);
    if (success) {
      return true;
    }
  }

  // 如果强制重试且所有接口都失败，再试一次
  if (forceRetry) {
    for (const endpoint of apiEndpoints) {
      const success = await tryFetch(endpoint);
      if (success) {
        return true;
      }
    }
  }

  return false;
};

// 获取拒赔操作人员列表
const fetchOperatorList = async () => {
  try {
    const res = await hxxp.get("/aiStaffUser/worker", {
      params: {positionCode: "PTN001"}
    })

    if (res.code === 100200) {
      operatorOptions.value = (res.data || []).map(staff => ({
        workNo: staff.workNo || staff.work_no,
        realName: staff.realName || staff.real_name
      }))

      if (operatorOptions.value.length === 0) {
        ElMessage.warning("当前无可用拒赔操作人员，请联系管理员配置")
      }
    } else {
      ElMessage.error(`获取操作人员列表失败：${res.msg || '未知错误'}`)
    }
  } catch (error) {
    console.error("获取操作人员列表失败:", error)
  }
}

// ---------------------- 11. 拒赔表单操作 ----------------------
// 提交拒赔申请
const handleSubmit = async () => {
  if (!rejectFormRef.value) return

  // 表单验证
  try {
    await rejectFormRef.value.validate()
  } catch (error) {
    ElMessage.error("表单验证失败，请检查标红字段")
    return
  }

  // 二次确认
  ElMessageBox.confirm(
      "确定提交拒赔申请吗？提交后将把报案状态更新为拒赔状态！",
      "提交确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
  ).then(async () => {
    submitLoading.value = true
    const loading = ElLoading.service({
      lock: true,
      text: "正在提交拒赔申请...",
      background: "rgba(255,255,255,0.7)"
    })

    try {
      const submitData = {
        reportNo: rejectForm.reportNo,
        registrationId: rejectForm.registrationId,
        preClaimId: rejectForm.verificationId, // 提交核赔号
        policyId: rejectForm.policyId,
        userId: rejectForm.userId,
        rejectReason: rejectForm.rejectReason,
        rejectStatus: Number(rejectForm.rejectStatus),
      }

      const res = await hxxp.post("/rejection/addRejection", submitData)

      if (res.code === 100200) {
        ElMessage.success(res.msg || "拒赔申请提交成功！")
        switchToView('list')
      } else {
        ElMessage.error(`提交失败：${res.msg || '未知错误'}`)
      }
    } catch (error) {
      console.error("提交拒赔申请失败:", error)
    } finally {
      submitLoading.value = false
      loading.close()
    }
  }).catch(() => {
    ElMessage.info("已取消提交")
  })
}

// 重置拒赔表单
const handleReset = () => {
  if (rejectFormRef.value) {
    rejectFormRef.value.resetFields()
    rejectForm.rejectReason = ""
    rejectForm.rejectStatus = "1"
    // 保留系统生成的ID和关联字段
    rejectForm.rejectionId = generateRejectionId()
  }
}

// ---------------------- 12. 页面初始化 ----------------------
onMounted(() => {
  getReportList()
})
</script>

<style scoped>
.claim-management-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  background-color: #fafafa;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  margin-top: 15px;
}

.list-card {
  min-height: 500px;
}

.main-card {
  background-color: #fff;
  padding: 32px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.info-collapse {
  border: 1px solid #f1f3f4;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 24px;
}

.el-collapse-item__header {
  background-color: #f8f9fa;
  font-weight: 500;
}

.el-collapse-item__content {
  padding: 20px;
}

.highlight-item {
  background-color: #f0f7ff;
  font-weight: 500;
}

.reject-form .el-form-item {
  margin-bottom: 28px;
}

.reject-form .el-form-item__help {
  margin-top: 4px;
  display: flex;
  justify-content: space-between;
}

.text-warning {
  color: #ffc107;
}

.char-count {
  color: #666;
  font-size: 12px;
}

.form-actions {
  margin-top: 40px;
  display: flex;
  justify-content: flex-end;
  gap: 16px;
}

.pagination {
  margin-top: 15px;
  text-align: right;
}

.empty-state {
  padding: 40px 20px;
  text-align: center;
  background-color: #fafafa;
  border-radius: 4px;
  margin: 10px 0;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .claim-management-container {
    padding: 16px;
  }

  .main-card {
    padding: 16px;
  }

  .el-collapse-item__content {
    padding: 12px;
  }

  .el-descriptions {
    column-count: 1 !important;
  }

  .form-actions {
    flex-direction: column;
    align-items: stretch;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>
